﻿using Leo.Common.MQ;
using Microsoft.Extensions.DependencyInjection;

namespace Leo.Common.RabbitMQ
{
    /// <summary>
    /// 依赖注入 扩展
    /// </summary>
    public static class DependencyInjectionExtension
    {
        /// <summary>
        /// 发现AppDomain中声明的队列
        /// </summary>
        /// <param name="builder"></param>
        private static void DiscoverTheQueueDeclaredInAppDomain(RabbitBuilder builder)
        {
            foreach (RabbitObjectBase participant in RabbitObjectScanner.ScanAppDomainForQueueDeclare(Array.Empty<string>()))
            {
                builder.Declare(participant);
            }
        }

        /// <summary>
        /// Rabbit 注入
        /// </summary>
        /// <param name="services"></param>
        /// <param name="config"></param>
        /// <param name="enableAutoDiscovery"></param>
        /// <returns></returns>
        public static RabbitBuilder AddRabbit(this IServiceCollection services, RabbitConfig config, bool enableAutoDiscovery)
        {
            ServiceCollectionServiceExtensions.AddSingleton<RabbitConfig>(services, config);
            RabbitBuilder rabbitBuilder = new RabbitBuilder(config, services);
            if (enableAutoDiscovery)
            {
                DependencyInjectionExtension.DiscoverTheQueueDeclaredInAppDomain(rabbitBuilder);
            }
            return rabbitBuilder;
        }


        /// <summary>
        /// Rabbit 注入
        /// </summary>
        /// <param name="services"></param>
        /// <param name="config"></param>
        /// <returns></returns>
        public static RabbitBuilder AddRabbit(this IServiceCollection services, RabbitConfig config)
        {
            return services.AddRabbit(config, false);
        }


        /// <summary>
        /// Rabbit 注入
        /// </summary>
        /// <param name="services"></param>
        /// <param name="config"></param>
        /// <param name="configure"></param>
        /// <returns></returns>
        public static IMessageQueueProvider AddRabbit(this IServiceCollection services, RabbitConfig config, Action<RabbitBuilder> configure)
        {
            RabbitBuilder rabbitBuilder = new RabbitBuilder(config, services);
            configure(rabbitBuilder);
            if (config.EnableQueueAutoDiscovery)
            {
                DependencyInjectionExtension.DiscoverTheQueueDeclaredInAppDomain(rabbitBuilder);
            }
            return rabbitBuilder.Build();
        }
    }
}
